package test;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.HashMap;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

/**
 * @author Administrator
 * 
 */
public abstract class AbstractFetionUser extends Thread {

	String RETURN = "\r\n";

	String MOBILE;

	String PASSWORD;

	String FETIONID;

	String FETIONURI;

	String SIPC_PROXY;

	Socket mySocket = null;

	OutputStream myOut = null;

	InputStream myIn = null;

	String nonce;

	public static HashMap map = new HashMap();
	public static int seq = 1;

	public AbstractFetionUser() {
	}

	public AbstractFetionUser(String mobile, String password) {
		this.MOBILE = mobile;
		this.PASSWORD = password;
	}

	public void keepAlive() {
		try {
			String data = "R fetion.com.cn SIP-C/2.0" + RETURN + "F: "
					+ FETIONID + RETURN + "I: 23" + RETURN + "Q: 20" + " R";
			write(data);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void run() {
		try {
			while (true) {
				System.out.println("mySocket=" + mySocket + "--"
						+ mySocket.isConnected());
				// keepAlive();
				byte[] responseBytes = read();
				if (responseBytes.length > 0) {
					String response = new String(responseBytes, "utf-8");
//					System.out
//							.println("Response Start--------------------------------------------------------------------");
//					System.out.println(response);
//					System.out
//							.println("Response End--------------------------------------------------------------------");
//					int p = response.indexOf("<results><contacts>");
//					if (p != -1) {
//					
//						response = response.replaceAll("<results><contacts>","");
//						response = response.replaceAll("</results></contacts>","");
//
//						System.out
//								.println("___________________________contactList="
//										+ response);
//						
//						DocumentBuilderFactory factory = DocumentBuilderFactory
//								.newInstance();
//						DocumentBuilder builder = factory.newDocumentBuilder();
//						Document doc = builder.parse(new ByteArrayInputStream(
//								response.trim().getBytes()));
//
//						Element root = doc.getDocumentElement();
//						NodeList userNL = root.getElementsByTagName("contact");
//
//						ArrayList list = (ArrayList) map.get(FETIONID);
//						for (int i = 0; i < userNL.getLength(); i++) {
//							Element nameNM = (Element) userNL.item(i);
//							String fetionUri = nameNM.getAttribute("uri");
//							Element perNM = (Element) nameNM
//									.getElementsByTagName("personal").item(0);
//							for (int j = 0; j < list.size(); j++) {
//								FetionUserInfo info = (FetionUserInfo) list
//										.get(j);
//								if (info.getFetionUri().equals(fetionUri)) {
//									list.remove(info);
//									String fetionId = getFetionId(fetionUri);
//									info.setFetionId(fetionId);
//									info.setFetionUri(fetionUri);
//									info.setNickname(perNM
//											.getAttribute("nickname"));
//									info.setSex(perNM.getAttribute("gender"));
//									info.setMobile(perNM.getAttribute("mobile-no"));
//									list.add(info);
//								} else {
//									FetionUserInfo newinfo = new FetionUserInfo();
//									String fetionId = getFetionId(fetionUri);
//									newinfo.setFetionId(fetionId);
//									newinfo.setFetionUri(fetionUri);
//									newinfo.setNickname(perNM
//											.getAttribute("nickname"));
//									newinfo
//											.setSex(perNM
//													.getAttribute("gender"));
//									newinfo.setMobile(perNM.getAttribute("mobile-no"));
//									list.add(newinfo);
//								}
//							}
//
//						}
//						for (int j = 0; j < list.size(); j++) {
//							FetionUserInfo info = (FetionUserInfo) list.get(j);
//							System.out
//									.println("++++++++++++++++++++++++fetionUri="
//											+ info.getFetionUri()
//											+ "------fetionId="
//											+ info.getFetionId()
//											+ "------online-notify="
//											+ info.getStatus()
//											+ "----------sex="
//											+ info.getSex()
//											+ "----------Nickname="
//											+ info.getNickname());
//						}
//						map.put(FETIONID, list);
//					}
//					int s = response.indexOf("<buddies>");
//					if (s != -1) {
//						int e = response.indexOf("</buddies>");
//						response = response.substring(s, e
//								+ "</buddies>".length());
//
//						System.out
//								.println("___________________________contactList="
//										+ response);
//
//						DocumentBuilderFactory factory = DocumentBuilderFactory
//								.newInstance();
//						DocumentBuilder builder = factory.newDocumentBuilder();
//						Document doc = builder.parse(new ByteArrayInputStream(
//								response.getBytes()));
//
//						Element root = doc.getDocumentElement();
//						NodeList userNL = root.getElementsByTagName("buddy");
//						ArrayList list = new ArrayList();
//
//						for (int i = 0; i < userNL.getLength(); i++) {
//							Element nameNM = (Element) userNL.item(i);
//							String fetionUri = nameNM.getAttribute("uri");
//							System.out.println("nameNM fetionUri=" + fetionUri);
//							String fetionId = getFetionId(fetionUri);
//							String online_notify = nameNM
//									.getAttribute("online-notify");
//							System.out.println(">>>>>>>>>>>>>fetionUri="
//									+ fetionUri + "------fetionId=" + fetionId
//									+ "----------------online-notify="
//									+ online_notify);
//							FetionUserInfo info = new FetionUserInfo();
//							info.setFetionId(fetionId);
//							info.setFetionUri(fetionUri);
//							info.setStatus(online_notify);
//							list.add(info);
//							getContactsInfo(fetionId,fetionUri);
//						}
//						map.put(FETIONID, list);
//
//					}
				}

				sleep(3000L);

				// keepAlive();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public int getQ() {
		return seq++;
	}

	public void getPersonalInfo(String fetionId) throws IOException {
		String data = "S fetion.com.cn SIP-C/2.0"
				+ RETURN
				+ "F: "
				+ fetionId
				+ RETURN
				+ "I: "
				+ getQ()
				+ RETURN
				+ "Q: "
				+ getQ()
				+ " S"
				+ RETURN
				+ "N: GetPersonalInfo"
				+ RETURN
				+ "L: 167"
				+ RETURN
				+ RETURN

				+ "<args><personal version=\"2\" attributes=\"all\" /><services version=\"\" attributes=\"all\" /><config version=\"2\" attributes=\"all\" /><mobile-device attributes=\"all\" /></args>";

		write(data);

	}

	public void getContactsInfo(String fetionId, String fetionUri)
			throws IOException {
		String data = "S fetion.com.cn SIP-C/2.0"
				+ RETURN
				+ "F: "
				+ fetionId
				+ RETURN
				+ "I: "
				+ getQ()
				+ RETURN
				+ "Q: "
				+ getQ()
				+ " S"
				+ RETURN
				+ "N: GetContactsInfo"
				+ RETURN
				+ "L: 137"
				+ RETURN
				+ RETURN

				+ "<args><contacts attributes=\"all\" extended-attributes=\"score-level\"><contact uri=\""
				+ fetionUri + "\" /></contacts></args>";

		write(data);

	}

	public byte[] read() throws IOException {
		byte[] buffer = new byte[1024 * 100];
		ByteArrayOutputStream bo = new ByteArrayOutputStream(1024);
		int c = 0;
		c = myIn.read(buffer);
		System.out.println("c:" + c);
		if(c>0)
		{
			bo.write(buffer, 0, c);
		}
		System.out.println("<-----" + bo.toString());

		return bo.toByteArray();
	}

	public void write(String data) throws IOException {
		myOut.write(data.getBytes("utf-8"));
		myOut.flush();

		System.out.println("----->" + data);
	}

	public void openSocket() throws Exception, IOException {
		if (SIPC_PROXY == null)
			return;

		try {
			mySocket = new Socket(getProxyIp(SIPC_PROXY),
					getProxyPort(SIPC_PROXY));
			myOut = mySocket.getOutputStream();
			myIn = mySocket.getInputStream();
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void closeSocket() throws Exception, IOException {
		if (myOut != null)
			myOut.close();

		if (myIn != null)
			myIn.close();

		if (mySocket != null)
			mySocket.close();
	}

	public String getProxyIp(String proxy) {
		return proxy.substring(0, proxy.indexOf(":"));
	}

	public int getProxyPort(String proxy) {
		return Integer.parseInt(proxy.substring(proxy.indexOf(":") + 1));
	}

	public String getFetionId(String fetionUri) {
		int p1 = fetionUri.indexOf(":");
		int p2 = fetionUri.indexOf("@");
		return fetionUri.substring(p1 + 1, p2);
	}

	public String findNonce(String src) {
		String rst = null;
		String flag = "nonce=\"";
		int p1 = src.indexOf(flag);
		int p2 = src.lastIndexOf("\"");
		rst = src.substring(p1 + flag.length(), p2);
		return rst;
	}

}
